package com.student.demo.config;

import com.student.demo.util.BaseException;
import com.student.demo.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.logging.Handler;

/**
 * @Author lsc
 * <p>token验证拦截器 </p>
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")		//调用实现yml中的配置属性
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if (token != null){
            int id = JwtUtil.getIdByToken(request);
            String number=JwtUtil.getNumberByToken(request);
            String role=JwtUtil.getRoleByToken(request);
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if(method.isAnnotationPresent(RolePermission.class)){
                RolePermission annotation = method.getAnnotation(RolePermission.class);
                if(!annotation.login()){
                    return true;
                }
            }
            if(method.isAnnotationPresent(RolePermission.class)){
                RolePermission annotation = method.getAnnotation(RolePermission.class);
                String roleRolePermission = annotation.role();
                if(StringUtils.isBlank(roleRolePermission)){
                    throw new BaseException("接口权限获取失败");
                }
                int i = roleRolePermission.indexOf(role);
                if(i==-1){
                    throw new BaseException("用户权限不足");
                }
            }
//            解密token信息
            boolean result = JwtUtil.verify(token,id,number,role,secret);
            if(result){
                System.out.println("通过拦截器");
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}


